package cn.serein.charging.order.rabbit;

import cn.serein.charging.order.config.RabbitMQConfiguration;
import cn.serein.charging.order.constant.OrderStatusConstant;
import cn.serein.charging.order.dao.mappers.OrderSuccessMapper;
import cn.serein.charging.order.dao.repository.OrderRepository;
import cn.serein.charging.order.pojo.po.ChargingBillSuccessPO;
import cn.serein.charging.order.pojo.po.OrderMQPO;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class RabbitMQConsumer {

//    @Autowired
//    private OrderSuccessMapper orderSuccessMapper;
    @Autowired
    private OrderRepository orderRepository;

    // 监听死信队列
    @RabbitListener(queues = RabbitMQConfiguration.DEAD_LETTER_QUEUE_NAME)
    // 这里的包很容易导错误
    public void consumerChargingQueue(OrderMQPO orderMQPo, Message message, Channel channel) throws IOException {

        // 死信队列
        log.debug("receive message:{}", orderMQPo);
        // 需要将订单记录中的状态由 正在充电中  修改为异常结束
        // update charging_bill_success
        // set bill_status = 3
        // where bill_id = orderNo and  bill_status = 1(充电中)

        // 下面的代码与业务耦合在一起了，可以采取提取出来

        /*// 以往是需要在xml文件中编写sql，但是这里使用mybatis-plus来实现
        //  mapper.update(entity, wrapper)
        ChargingBillSuccessPO po = new ChargingBillSuccessPO();
        po.setBillStatus(OrderStatusConstant.ORDER_STATUS_EXCEPTION_END);

        // 相当于where子句  eq  等于   。。。。
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("bill_id", orderMQPo.getOrderNo());
        wrapper.eq("bill_status", OrderStatusConstant.ORDER_STATUS_PROGRESS);

        orderSuccessMapper.update(po, wrapper);*/
        orderRepository.updateOrderStatusFromProcess2ExceptionEnd(orderMQPo.getOrderNo());

        // 手动确认消息  并添加ack,如果去除，那么队列一直存在
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);

    }

}
